package com.glgc.projecti.entity.base;

import java.io.Serializable;
import java.lang.reflect.InvocationTargetException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.glgc.projecti.common.CopyUtils;

/**
 * DTO基类
 * 
 * @author jacky
 * 
 */
public abstract class BaseDto<T extends IntIdentity> implements Serializable {

	private static final long serialVersionUID = 1L;
	private static final SimpleDateFormat sdf = new SimpleDateFormat(
			"yyyy-MM-dd");
	
	private static final SimpleDateFormat sdf2 = new SimpleDateFormat(
			"yyyy-MM-dd HH:mm:ss");

	protected String id;

	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		IntIdentity other = (IntIdentity) obj;
		if (id == null) {
			if (other.id != null)
				return false;
		} else if (!id.equals(other.id))
			return false;
		return true;
	}

	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + ((id == null) ? 0 : id.hashCode());
		return result;
	}
	
	public static String date2String(Date date) {
		if (date != null) {
			return sdf.format(date);
		} else {
			return "";
		}
	}
	
	public static String date2String2(Date date) {
		if (date != null) {
			return sdf2.format(date);
		} else {
			return "";
		}
	}

	@SuppressWarnings("unchecked")
	public <G extends BaseDto<T>> G convertToDto(T t) {
		try {
			CopyUtils.copyProperty(this, t);
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			e.printStackTrace();
		}
		return (G) this;
	}

	@SuppressWarnings("unchecked")
	public <G extends BaseDto<T>> List<G> convertToDtoList(List<T> ts) {
		List<G> gs = new ArrayList<G>();
		try {
			for (T t : ts) {
				G dto = (G) this.getClass().newInstance().convertToDto(t);
				gs.add(dto);
			}
		} catch (InstantiationException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		}
		return gs;
	}

	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}

}
